package com.example.fp.cgc.controller

import com.example.fp.cgc.entity.Message
import com.example.fp.cgc.mapper.MessageMapper
import com.example.fp.cgc.util.PageUtil
import com.example.fp.cgc.util.SpringUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.ModelAndView
import springfox.documentation.swagger2.annotations.EnableSwagger2
import kotlin.math.min

/**
 * @since 2020-02-19
 * @author 蔡
 */
@RestController
@RequestMapping
@EnableSwagger2
open class MessageController {

    @Autowired
    @Lazy
    lateinit var messageMapper: MessageMapper

    companion object {
        val messageController: MessageController by lazy {
            SpringUtil.getBean(MessageController::class.java)
        }
    }

    /**
     * 历史记录获取
     */
    @RequestMapping(value = ["/messageHistory/{uid}&{oid}"], method = [RequestMethod.GET])
    open fun messageHistory(
            @PathVariable("uid") uid: Int,
            @PathVariable("oid") oid: Int
    ): List<Message> {
        return messageMapper.getHistory(uid, oid)
    }

    /**
     * 历史记录获取
     * 有分页功能
     * 可进行搜索
     */
    @GetMapping(value = ["/chatHistory1ByText/{uid}&{oid}&{page}"])
    open fun messageHistoryByText(
            @PathVariable("uid") uid: Int,
            @PathVariable("oid") oid: Int,
            @PathVariable("page") page: Int,
            @RequestParam(required = true, defaultValue = "") text: String,
            model: Model): ModelAndView {
        val size = 20

        val count = if (text.isNotEmpty()) {
            model.addAttribute("text", text)
            messageMapper.getMessageCountByText(uid, oid, text)
        } else {
            messageMapper.getMessageCount(uid, oid)
        }

        model.addAttribute("text", text)

        if (count == 0) {
            model.addAttribute("count", count)
            return ModelAndView("chatByCgc/chatHistory1", "historyModel", model)
        } else {

            val pageSize = 10

            val pageData = PageUtil.getPage(page, count, pageSize)

            if (text.isNotEmpty()) {
                val messageList: List<Message> = messageMapper.searchText(uid, oid, text, pageData.currLoc, size)
                model.addAttribute("messageList", messageList)
            } else {
                val messageList: List<Message> = messageMapper.historyById(uid, oid, pageData.currLoc, size)
                model.addAttribute("messageList", messageList)
            }

            val currMaxPage = min(page + 10, pageData.maxPage)

            model.addAttribute("pageNo", page)
            model.addAttribute("maxpage", pageData.maxPage)
            model.addAttribute("currMaxPage", currMaxPage)

            return ModelAndView("chatByCgc/chatHistory1", "historyModel", model)
        }
    }
}